package com.interesting.client.UI.home;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.interesting.R;
import com.interesting.base.http.HttpUtil;
import com.interesting.base.utils.SQLiteUtil;
import com.interesting.client.adapter.MessageListAdapter;
import com.interesting.client.application.AppHolder;
import com.interesting.client.bean.Message;
import com.interesting.client.support.pulltorefresh.PullToRefreshBase;
import com.interesting.client.support.pulltorefresh.PullToRefreshBase.OnLastItemVisibleListener;
import com.interesting.client.support.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.interesting.client.support.pulltorefresh.PullToRefreshListFragment;

/**
 * 
 * 
 * 醉新 的fragment
 */
public class RecentFragment extends PullToRefreshListFragment implements OnRefreshListener<ListView>,
		OnLastItemVisibleListener {

	private MessageListAdapter mesgAdapter;
	private List<Message> mesg_data = new ArrayList<Message>();
	private int currentPage = 0, totalPages = 1;
	private SQLiteUtil sqllite;
	private RadioButton first, second, third;
	RadioGroup radioGroup;
	// private static String TYPE = "content_type";// 显示信息的类别 ,这是Bundle的key
	private String type;// 显示信息的类别 ,这是Bundle的value
	private ActionBar bar;

	public static RecentFragment newInstance() {

		RecentFragment fragment = new RecentFragment();
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		bar = getSherlockActivity().getSupportActionBar();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		radioGroup = (RadioGroup) bar.getCustomView().findViewById(R.id.recent_fragment_radiogroup_three);
		first = (RadioButton) getSherlockActivity().getSupportActionBar().getCustomView()
				.findViewById(R.id.hot_radiogroup_day);
		second = (RadioButton) getSherlockActivity().getSupportActionBar().getCustomView()
				.findViewById(R.id.hot_radiogroup_week);
		third = (RadioButton) getSherlockActivity().getSupportActionBar().getCustomView()
				.findViewById(R.id.hot_radiogroup_month);
		if(type==null)
		type = radioGroup.getChildAt(0).getTag().toString();
		if(type.equals("2")){
			first.setChecked(false);
			second.setChecked(true);
			third.setChecked(false);
		}else if(type.equals("3")){
			first.setChecked(false);
			second.setChecked(false);
			third.setChecked(true);
		}
		bar.setDisplayShowCustomEnabled(true);
		return super.onCreateView(inflater, container, savedInstanceState);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		barRadion();
		mesgAdapter = new MessageListAdapter(getSherlockActivity(), mesg_data);

		pullToRefreshListView.setOnRefreshListener(this);
		pullToRefreshListView.setOnLastItemVisibleListener(this);

		getListView().setAdapter(mesgAdapter);
		if (getCurrentState(savedInstanceState) == FIRST_TIME_START) {
			pullToRefreshListView.startRefreshNow();
			this.hide();
		}
		/** 点击listview的item 进入查看评论界面 */
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

				Intent intent_comment = new Intent(getSherlockActivity(), CommentActivity.class);
				// 发送信息内容到下个界面
				intent_comment.putExtra("message", mesg_data.get(position - 1));
				startActivityForResult(intent_comment, 21);// 进入信息详情界面，
			}
		});

		/** 长按分享 */
		getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {

				Intent intentshare = new Intent(Intent.ACTION_SEND);
				intentshare.setType("text/plain");
				intentshare.putExtra(Intent.EXTRA_SUBJECT, "share");
				intentshare.putExtra(Intent.EXTRA_TEXT, mesg_data.get(position - 1).getContent());
				startActivity(Intent.createChooser(intentshare, "醉有趣分享"));
				return true;
			}
		});

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		return super.onOptionsItemSelected(item);

	}

	@Override
	public void onLastItemVisible() {
		if (currentPage < totalPages) {
			showFooterView();
			currentPage++;
			new MessageRefresh().execute(type);
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		currentPage = 1;
		new MessageRefresh().execute(type);
	}

	/** 监听actionbar 的被选择的radioButton,从而获得信息类别 */
	private void barRadion() {

		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				Log.d("TAG", "换头" + type);
				pullToRefreshListView.onRefreshComplete();
				type = group.findViewById(checkedId).getTag().toString(); // 获取被选择的类别--{day,week,month}
				pullToRefreshListView.startRefresh();
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			Message mesg = (Message) data.getParcelableExtra("message");
			for (int i = 0; i < mesg_data.size(); i++) {
				if (mesg.getId().equals(mesg_data.get(i).getId())) {
					mesg_data.set(i, mesg);
					break;
				}
			}
			mesgAdapter.notifyDataSetChanged();
		}
	}

	/** 信息刷新 */
	class MessageRefresh extends AsyncTask<String, Void, String> {
		public  final String[] allColumns = { SQLiteUtil.HOME_ID, SQLiteUtil.HOME_JOKEID, SQLiteUtil.HOME_JOKESTATE };
		@Override
		protected String doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("act", "drunkenList");
			map.put("currentPage", currentPage + "");
			map.put("date", params[0]); // 信息种类
			map.put("rowCountPerPage", "7");
			return HttpUtil.post(map);
		}

		@Override
		protected void onPostExecute(String result) {
			JSONObject response = HttpUtil.parseResult(result);
			if (response != null) {
				try {
					if (currentPage == 1)
						mesg_data.clear();
					Gson gson = new Gson();
					List<Message> dataList = gson.fromJson(response.getString("dataList"),
							new TypeToken<List<Message>>() {
							}.getType());
					
					sqllite=AppHolder.getInsatnce().dbAdapter;
					
					// lite数据库扫描看是否有数据
					String ids="";
					for (int i = 0; i < dataList.size(); i++) {
							ids+="'"+dataList.get(i).getId()+"'";
						if(i!= dataList.size()-1)
							ids+=",";
					}
					sqllite=AppHolder.getInsatnce().dbAdapter;
					Cursor cursor =sqllite.getWritableDatabase().query(SQLiteUtil.TABLE_JOKE, allColumns,
							"jokeid IN ("+ids+")",null, null, null, null);
					Log.d("TAG","已投票数量:"+cursor.getCount()+"");
					cursor.moveToFirst();
					while (!cursor.isAfterLast()) {
						
						for (int i = 0; i < dataList.size(); i++) {
							if(dataList.get(i).getId().equals(cursor.getString(1))){
								dataList.get(i).setStatus(Integer.parseInt(cursor.getString(2)));
								break;
							}
						}
						cursor.moveToNext();
					}
					cursor.close();
					
					
					for (int i = 0; i < dataList.size(); i++) {
						mesg_data.add(dataList.get(i));
					}
					totalPages = Integer.parseInt(response.getString("totalPage"));
					currentPage = Integer.parseInt(response.getString("currentPage"));
				} catch (Exception e) {
					e.printStackTrace();

				}
			} else {
				mesg_data.clear();
			}
			dismissFooterView();
			pullToRefreshListView.onRefreshComplete();
			mesgAdapter.notifyDataSetChanged();

			show();
			super.onPostExecute(result);
		}
	}
}
